<?php

namespace app\admin\controller;
use app\common\controller\Admin;
use app\ads\controller\Api;

use function AlibabaCloud\Client\value;

/**
 * 素材管理
 *
 * @Author 小邓
 * @DateTime 2022-11-05
 */
class Material extends Admin {

	public function _initialize() {
		parent::_initialize();
        $action = ACTION_NAME;
        $this->assign(compact('action'));
        $this->setMeta("文案素材公众库");
        $this->uploadDownTxt = new \app\admin\model\UploadDownTxt();
    }

    /**
     * 所有子页都用这个方法处理,
     * /admin/material/wenan-index_1_1.html
     * 后面有个 1_1
     * 第一个1表示平台 platform_ids
     * 第二个1表示平台 类型 1文案 3视频 6图片...
     *
     * @Author 小邓
     * @DateTime 2022-11-05
     * @return void
     */
    public function _empty(){
        $action = ACTION_NAME;

        // 记忆 平台 
        if(input('get.platform_ids')){
            session('platform_ids', input('get.platform_ids'));
        }else{
            if( session('platform_ids') ){
                $_GET['platform_ids'] = session('platform_ids');
            }
        }
        // 记忆 模板
        $mb = input('get.mb', 1);
        if(input('get.mb')){
            $mb = input('get.mb');
            session('mb', input('get.mb'));
        }else{
            if( session('mb') ){
                $mb = session('mb');
            }
        }

        //从ACTION中取 platform_ids和type
        $arr    =  explode("_", $action);
        if(isset($arr[1]) && !isset( $_GET['platform_ids']) ) {
            $_GET['platform_ids'] = $arr[1];
        }
        if(isset($arr[2]) && !isset( $_GET['type'])) {
            $_GET['type'] = $arr[2];
        }
        if(!is_numeric($_GET['platform_ids'])){
            $_GET['platform_ids'] = 1; //百度平台
        }
        $keyword = trim(input('get.keyword'));
        $map     = [];
        $idinfo  = [];
        if($keyword){
            $map['content'] = ['like', "%$keyword%"];
            //如果搜索的是ID
            if (is_numeric ($keyword)) {
                $idinfo = db('ads_material')->where("id", $keyword)->find();
                $_GET['type'] = $idinfo['type'];
                $_GET['platform_ids'] = 1;
                unset($map['content']);
                $map['id'] =$keyword;
            }
        }
        $order = 'id desc';
        $uid   = session('user_auth.uid');
        $db    = "ads_material";//公众库
        if(stristr(ACTION_NAME, 'my')){
            $follow = db('ads_material_my')->where("uid",$uid )->column('ads_material_id');
            $db = "ads_material_my"; //编辑台 工作台
            $order = stristr(ACTION_NAME, 'mycenter')  ? 'update_time desc' : 'id desc';
        }
        $order1 = $this->getOrder();
        $order = $order1 ?: $order;
        // echo $order;exit;
        $map_sql = $this->mapBuild();
        if(isset($map['id'] )){
            $map_sql = "1=1";
        }
        $pageSize = 50;
        $list = db( $db )->where($map)->order( $order )->where($map_sql)->paginate( $pageSize, false, [ 'type'=> 'page\Page' ,'query' => request()->param()] );
        // echo db('ads_material_my')->getLastSql();exit;
        $allData = $this->getMyData();
        $type          = array_column($allData['type'], 'name', 'id');
        $channel       = array_column($allData['channel'], 'name', 'id');
        $channel2      = array_column($allData['channel'], 'icon', 'id');
        $category_id   = array_column($allData['category_id'], 'name', 'id');
        $platform_ids  = array_column($allData['platform_ids'], 'name', 'id');
        $hotids        = array_column($allData['hot'], 'name', 'id');
        $hotids2       = array_column($allData['hot'], 'icon', 'id');
        $tag_ids       = array_column($allData['tag_ids'], 'name', 'id');
        $book_id       = array_column($allData['book_id'], 'name', 'id');
        $magnitude_num = array_column($allData['magnitude_num'], 'name', 'id');
        $ids = array_column($list->all(), "id");
        //判断是否添加过工作台
        $follow = db("ads_material_my")->where("uid=".$uid)->where("ads_material_id", "in", $ids)->column('id', "ads_material_id");
        //判断是否上报到公众库
        $isuploads = [];
        if(stristr($action, 'mycenter')){
            $isuploads = db("ads_material")->where("ads_material_my_id", "in", $ids)->column('id', "ads_material_my_id");
        }
        $i = 1;
        $pagestr = input('get.page', 1); //翻页序号
        foreach ($list as $k => $v) {
            $v['type_zh']         = $type[$v['type']]??"-";
            $v['channel_zh']      = $channel[$v['channel']]??"-";
            $channelicon = $channel2[$v['channel']]??"";
            if($channelicon){
                // $v['channel_zh'] = '<i class="iconfont '.$channelicon.'"></i> ';
                $v['channel_zh'] =  $v['channel_zh']  ==  "男频" ?"男":"女";
            }
            $v['content_old'] = "";
            if($db == 'ads_material_my'){
                $v['content_old'] = db("ads_material")->where("id=".$v['ads_material_id'])->value('content');
                $v['content_old']  = str_replace([PHP_EOL,"\r\n"],"####",htmlspecialchars_decode($v['content_old'],ENT_QUOTES ));
                // dump( $v['content_old']);exit;
                $v['content_old']  =  str_replace(["  ", "   "], "", $v['content_old']);
                $v['content_old']  =  str_replace(["########"], "####", $v['content_old']);
            }
            $v['content_old'] = str_replace(["\"", "'"],"”", htmlspecialchars_decode($v['content_old'], ENT_QUOTES ) );
            $v['category_id_zh']  = $category_id[$v['category_id']]??"-";
            $v['platform_ids_zh'] = $this->changeTozh($platform_ids, $v['platform_ids'], 'platform_ids');
            $v['hot'] = $v['hot']??0;
            $hot = $hotids[$v['hot']]??"";
            $icon = $hotids2[$v['hot']]??"";
            if($icon){
                $hot = '<i class="iconfont '.$icon.'"></i> '.$hot;
            }
            // $v['hot_zh'] = $this->changeTozh($hotids, $v['hot'], 'hot');//文字版本
            $v['hot_zh'] = $this->changeToImg($hotids2, $v['hot'], 'hot'); //图标版本
            $v['tag_ids_zh']      = $this->changeTozh($tag_ids, $v['tag_ids'], 'tag_ids');
            $v['book_id_zh']      = $book_id[$v['book_id']]??"-";
            $v['book_id_zh']      = mb_substr($v['book_id_zh'],0,4, 'utf-8');
            $v['is_follow']       = $follow[$v['id']]??0;
            $v['is_upload']       = $isuploads[$v['id']]??0;
            $v['magnitude_num_zh'] = $magnitude_num[$v['magnitude_num']]??0;
            $v['content'] = str_replace(["\"", "'"],"”", htmlspecialchars_decode($v['content'], ENT_QUOTES ) );
            $v['content_zh']  =  $v['content'];
    
            $v['content_zh2'] = douyin_str_format($v['content']);
            // dump($v['content_zh2'] );exit;
            if($keyword){
                $v['content_zh']  = str_replace($keyword, "<em>".$keyword."</em>",  $v['content']);
                $v['content_zh2'] =  str_replace($keyword, "<em>".$keyword."</em>",  $v['content_zh2']);
            }
            // $v['show_time'] = $v['update_time'] == 0 ? date('Y-m-d H:i:s', $v['create_time']) : date('Y-m-d H:i:s', $v['update_time']);
            $v['show_time'] = date('Y-m-d H:i:s', $v['create_time']) ; //时间
            $v['num'] =  $i+($pageSize*($pagestr-1)); //序号
            $list[$k] = $v;
            ++$i;
        }
        $page = $list->render();
        $this->assign(compact('keyword', 'list', 'page','mb'));
        $this->searchCate('search',  $idinfo); //搜索筛选
        $platform_id = input('get.platform_ids');
        $typeid = $arr[2]??input('get.type');
        $menu_name = $type[$typeid]??'';
        $this->setMeta($menu_name);
        $p_type = $platform_id.'_'.$typeid;
        $this->assign(compact('menu_name', 'p_type'));
        $this->getUserList(); // 工号列表 
        $platform_id = $arr[1]??input('param.platform_ids');
        if(input('param.platform_ids')){
            $platform_id = input('param.platform_ids');
        }
        $platform_id = $idinfo['platform_ids']??$platform_id;
        $this->assign(compact('platform_id', 'platform_id'));
        $type = $idinfo['type']??$typeid;
        $this->assign(compact('type'));
        $jumpurl = url()."?". http_build_query(request()->param());
        $this->assign(compact('jumpurl'));

        $view = view("material/index");
        //文案
        if(in_array($type, [1, 2, 24])){
            $view = view("material/index");
            if(stristr($action, 'mycenter')){
                $this->setMeta("工作台");
                $view =  view("material/mycenter");
            }
            if(stristr($action, 'my_')){
                $this->setMeta("编辑台");
                $view =  view("material/my");
            }
        }
        
        //文案 - 抖音
        if(in_array($type, [1, 2, 24]) &&  in_array($platform_id, [3,4])){
            $view = view("material_douying/index");
            if(stristr($action, 'mycenter')){
                $this->setMeta("工作台");
                $view =  view("material_douying/mycenter");
            }
            if(stristr($action, 'my_')){
                $this->setMeta("编辑台");
                $view =  view("material_douying/my");
            }
        }

        //图片
        if(in_array($type, [6, 7, 71, 72])){
            $view = view("material_media/images");
            if(stristr($action, 'mycenter')){
                $this->setMeta("工作台");
                $view =  view("material_media/images_mycenter");
            }
        }

        //视频
        if(in_array($type, [3,4,5])){
            $view = view("material_media/video");
            if(stristr($action, 'mycenter')){
                $this->setMeta("工作台");
                $view =  view("material_media/video_mycenter");
            }
        }

        //视频版面
        if($type == 12){
            $view = view("material_media/banmian");
        }

        //BGM
        if(in_array($type, [13,131])){
            $view = view("material_media/bgm");
        }

        //模板
        if($type == 14){
            $view = view("material_douying/module");
        }
        //模板编辑台
        if($type == 15){
            $view = view("material_douying/module_edit");
        }
        return $view;
    }

    //公用查询条件
    private function mapBuild(){ 
        $platform_ids = input('get.platform_ids');
        $map = "1=1";
        if ($platform_ids && $platform_ids!=999999) {
            $map .= " and FIND_IN_SET($platform_ids, platform_ids)";
        }
        $tag_ids = input('get.tag_ids');
        if ($tag_ids && $tag_ids!=999999) {
            $map .= " and FIND_IN_SET($tag_ids, tag_ids)";
        }

        $type = input('get.type');
        $arr    =  explode("_",ACTION_NAME);
        if(isset($arr[2]) && !$type) {
            $type= $arr[2];
        }
        //如果不是编辑器或工作台，则不需要用这个筛选了
        if ($type && $type!=999999 ) {
            if(stristr(ACTION_NAME, 'my')){
                if($arr[2] == 1){
                    $map .= " and type in (1,2)";
                }
                if($arr[2] == 6){
                    $map .= " and type in (6,7,71,72)";
                }
                if($arr[2] == 3){
                    $map .= " and type in (3,4,5,12)";
                }
            }else{
                $map .= " and type=$type";
            }
        }
        // echo $map;exit;
        $channel = input('get.channel');
        if ($channel && $channel!=999999 ) {
            $map .= " and channel=$channel";
        }
        $category_id = input('get.category_id');
        if ($category_id && $category_id!=999999 ) {
            $map .= " and category_id=$category_id";
        }
        $book_id = input('get.book_id');
        if ($book_id && $book_id!=999999 ) {
            $map .= " and book_id=$book_id";
        }
        $uid = input('get.uid');
        if ($uid && $uid!=999999 ) {
            $map .= " and uid=$uid";
        }
        //只有工作台和编辑器 才
        $suid = session('user_auth.uid');
        if(session('user_auth.group')!=999 && stristr(ACTION_NAME, 'my') ){
            if(stristr(ACTION_NAME, 'mycenter')){
                $uids = $this->getUids($suid);
                $map .= " and uid in (".implode(",", $uids).")";
                // echo $map;exit;
            }else{
                $map .= " and uid=$suid";
            }
        }
        // 工作台
        if(stristr(ACTION_NAME, 'mycenter_')){
            $map .= " and is_edit=2";
        }
        // 编辑器
        if(stristr(ACTION_NAME, 'my_')){
            // $map .= " and is_edit=1";
        }
        // echo $map;exit;
        $hot = input('get.hot');
        if ($hot && $hot!=999999  && !input('get.keyword')) {
            $map .= " and FIND_IN_SET($hot, hot)";
        }
        // $startdata = date("Y-m-d", strtotime("-0 days"));
        $startdata = date("2022-10-20");
        $enddata  =  date("Y-m-d");
        // 编辑台
        if(stristr(ACTION_NAME, 'my_')){
            $startdata = date("Y-m-d", strtotime("-0 days"));
            $startdata1 = strtotime($startdata);
            $enddata1   = strtotime($enddata." 23:59:59");
            $map .= " and update_time>=$startdata1 and update_time<=$enddata1";
        }
        //如果有筛选，则不用时间区间不然结果出不来了
        if(input('get.startdata') && !input('get.keyword')){
            $startdata = (input('get.startdata'));
            $enddata   = (input('get.enddata'));
            $startdata1 = strtotime($startdata);
            $enddata1   = strtotime($enddata." 23:59:59");
            if(stristr(ACTION_NAME, 'mycenter_')){
                $map .= " and update_time>=$startdata1 and update_time<=$enddata1";
            }else{
                $map .= " and create_time>=$startdata1 and create_time<=$enddata1";
            }
        }else{
            if(stristr(ACTION_NAME, 'mycenter_')){
                $startdata = date("Y-m-d", strtotime("-0 days"));
                $startdata1 = strtotime($startdata);
                $enddata1   = strtotime($enddata." 23:59:59");
                $map .= " and update_time>=$startdata1 and update_time<=$enddata1";
            }
        }
        // echo $map;exit;
        if(input('get.my_id')){
            $map = "id=".input('get.my_id');
        }
        //爆款
        if(stristr(ACTION_NAME, 'hot_')){
            //1，爆，2量，3量级大于1万，4评分95分以上
            $map .= ' and ( '.$this->hotLevelSearch().")";
        }

        //内部
        if(stristr(ACTION_NAME, 'inside_')){
            $map .= " and hot=3";
        }

        $this->assign(compact('startdata', 'enddata'));
        return $map;
    }

    private function hotLevelSearch() {
        $map = "";
        $hot_leval = input('get.hot_level', 999999);
        // echo $hot_leval;exit;
        $exp = $hot_leval  == 999999 ? 'or' : 'and';
        if( $hot_leval == 999999 || $hot_leval == 1) {
            $map .= " {$exp} find_in_set(1, hot)";
        }

        if( $hot_leval == 999999 || $hot_leval == 2) {
            $map .= " {$exp} find_in_set(2, hot)";
        }

        if( $hot_leval == 999999 || $hot_leval == 3) {
            $map .= " {$exp} magnitude_num>=10000";
        }

        if( $hot_leval == 999999 || $hot_leval == 4) {
            $map .= " {$exp} score>=95";
        }
        $map = ltrim($map, "or ");
        $map = ltrim($map, "and ");
        // echo $map;exit;
        return $map?:'1=1';
    }

    // 列表显示 多个平台 或标签时，展示多个颜色
    private function changeTozh($data, $str, $ptype) {
        $arr = explode(',', $str);
        $html = '';
        $arr2 = ["#6893c4","#3f8e20","#a0a4bf","#aeabf9","#5faf84","#8342c4","#0b743e","#472e9c","#2f263e"];
        $arr2 = ["#a69ab9", "#8c72e3", "#27764e", "#43aae5", "#afad5f", "#d79191", "#a0a4bf"];
        $arr3 = array_reverse($arr2);
        foreach ($arr as $k => $v) {
            if($ptype == 'platform_ids'){
                $color = $arr2[$k] ?? '';
                $html .= '<span class="label label-success" style="background-color:'.$color .'">';
            }else{
                $color = $arr3[$k] ?? '';
                $html .= '<span class="label label-success" style="background-color:'.$color.'">';
            }
            if($k % 4 == 0){
                // $html .= "<br/>";
            }
            $html .= $data[$v]??"-";
            $html .= "</span>&nbsp;";
        }
        return $html;
    }

    private function changeToImg($data, $str, $ptype) {
        $arr = explode(',', $str);
        $html = '';
        foreach ($arr as $hot) {
            $html .= '<i class="iconfont '.$data[$hot].'"></i>';
        }
        return $html;
    }

    
    public function getMyData() {
        $map = [];
        //男女频道 筛选 分类标签 也筛选
        if( input('get.channel') && input('get.channel') != 999999) {
            // $map["name"] = input('get.channel') == 1 ? "男频":"女频";
        }
        $arr    =  explode("_",ACTION_NAME);
        $curlType = ''; //wenan,img,video,bgm
        if(isset($arr[0]) ) {
            $arr2 = explode("-",$arr[0]);
            $curlType = $arr2[0];
        }
        $category = db('ads_material_category')->field("id,name as sex, title as name")->where( $map)->where("find_in_set('{$curlType}', types)")->order('sort desc,id asc')->select();
        //按不同地方显示不同标签
		$tags     = db('ads_material_tag')->field("id,name as sex, title as name")->where("find_in_set('{$curlType}', types)")->where( $map)->order('sort asc,id asc')->select();
		// $tags     = db('ads_material_tag')->field("id,name as sex, title as name")->where( $map)->order('sort asc,id desc')->limit(1000)->select();
        $books    = db('ads_material_book')->field("id,name as sex, title as name")->where( $map)->order('sex desc,sort desc,id asc')->limit(1000)->select();
        return [
			'platform_ids' => [
                // ['id' => 999999, 'name' => "全部", 'icon' =>""],
				['id' => 1, 'name' => "百度", 'icon' =>"icon-baidu"],
				['id' => 2, 'name' => "知乎", 'icon' =>"icon-shejiaotubiao-10"],
				['id' => 3, 'name' => "抖音", 'icon' =>"icon-douyin"],
				['id' => 4, 'name' => "微博", 'icon' =>"icon-weibo"],
				['id' => 5, 'name' => "腾讯", 'icon' =>"icon-weixin"],
				['id' => 6, 'name' => "其它", 'icon' =>"icon-qita"],
			],
            'type' => [
                // ['id' => 999999, 'name' => "全部"],
                ['id' => 1, 'name' => "文案素材公众库", 'types' => [1, 2, 24]],
                ['id' => 2, 'name' => "爆款文案", 'types' => [1, 2, 24]],
                ['id' => 3, 'name' => "起量视频", 'types' => [3, 4, 5]],
                ['id' => 4, 'name' => "视频成品", 'types' => [3, 4, 5]],
                ['id' => 5, 'name' => "视频素材", 'types' => [3, 4, 5]],
                ['id' => 6, 'name' => "图片公众库", 'type' => [6,7] ],
                ['id' => 7, 'name' => "图片爆款库", 'type' => [6,7] ],
                ['id' => 71, 'name' => "内裤图", 'type' => [6,7] ],
                ['id' => 72, 'name' => "版面库", 'type' => [6,7] ],
                // ['id' => 8, 'name' => "男主名字"],
                // ['id' => 9, 'name' => "女主名字"],
                // ['id' => 10, 'name' => "男配名字"],
                // ['id' => 11, 'name' => "女配名称"],
                ['id' => 12, 'name' => "视频版面"],
                ['id' => 13, 'name' => "音乐公众库"],
                ['id' => 131, 'name' => "音乐内部库"],
            ],
            'channel' => [
                ['id' => 999999, 'name' => "全部", 'icon' =>""],
				['id' => 1, 'name' => "男频", "sex"=> "男频", 'icon' =>"icon-guzhuangnansheng"],
				['id' => 2, 'name' => "女频", "sex"=> "女频", 'icon' =>"icon-nvshi"],
			],
			'category_id' => array_merge([['id' => 999999, 'name' => "全部"]], $category),
			'tag_ids'     => array_merge([['id' => 999999, 'name' => "全部"]], $tags),
            'book_id'     => array_merge([['id' => 999999, 'name' => "全部"]], $books),
            'hot' => [
                ['id' => 999999, 'name' => "全部", 'icon' =>""],
				['id' => 1, 'name' => "爆", 'icon' =>"icon-redu"],
				['id' => 2, 'name' => "起", 'icon' =>"icon-redu1"],
				['id' => 3, 'name' => "内", 'icon' =>"icon-weixingongzhonghao"],
				['id' => 4, 'name' => "外", 'icon' =>"icon-guanggao"],
				['id' => 5, 'name' => "新", 'icon' =>"icon-xinpin"],
			],
            'magnitude_num' => [
                ['id' => 100, 'name' => "100"],
                ['id' => 1000, 'name' => "1千"],
                ['id' => 2000, 'name' => "2千"],
                ['id' => 5000, 'name' => "5千"],
                ['id' => 10000, 'name' => "1万"],
                ['id' => 20000, 'name' => "2万"],
                ['id' => 50000, 'name' => "5万"],
                ['id' => 100000, 'name' => "10万"],
            ],
		];
    }

	/**
	 * 分类筛选
	 *
	 * @Author 小邓
	 * @DateTime 2022-11-05
	 * @return void
	 */
	public function searchCate($act = 'search',  $idinfo) {
        $type   = input('get.type');
        $arr    =  explode("_",ACTION_NAME);
        if(isset($arr[2]) && !$type) {
            $type = $arr[2];
        }
		$dataArr = $this->getMyData();
        $search  = '';
        $url     = url();
        $param   = input('get.');
        $arrD = [
            "channel"      => ["name" => "频道", "input_type" => 'radio', 'en_name' => 'channel', 'required'=> 0],
            "platform_ids" => ["name" => "平台", "input_type" => 'checkbox', 'en_name' => 'platform_ids', 'required'=> 1],
            "category_id"  => ["name" => "分类", "input_type" => 'radio', 'en_name' => 'category_id', 'required'=> 0],
            'type'         => ["name" => "类型", "input_type" => 'radio', 'en_name' => 'type', 'required'=> 0],
            "tag_ids"      => ["name" => "标签", "input_type" => 'checkbox', 'en_name' => 'tag_ids', 'required'=> 0],
            "book_id"      => ["name" => "书名", "input_type" => 'radio', 'en_name' => 'book_id', 'required'=> 0],
            "hot"          => ["name" => "热度", "input_type" => 'checkbox', 'en_name' => 'hot', 'required'=> 0],
            "magnitude_num"  => ["name" => "量级", "input_type" => 'radio', 'en_name' => 'magnitude_num', 'required'=> 0]
        ];
        // 默认给个值
        foreach ($dataArr as $key => $value) {
            foreach ($value as $k => $v) {
                 $dataArr[$key][$k]['ischecked'] = 0;
            }
        }
        foreach ($dataArr as $key => $value) {
            $style = '';
            //筛选不显示 分类 频道 类型
            if($key == 'category_id' || $key == 'channel'  || $key == 'type'  || $key == 'magnitude_num'  ){
                $style = "display:none";
            }
            //如果是编辑器，隐藏其它只保留 平台
            if( stristr(ACTION_NAME,'my_')){
                if($key != 'platform_ids'){
                    $style = "display:none";
                }
            }

            if( stristr(ACTION_NAME,'bgm_')){
                if($key == 'platform_ids'|| $key == 'hot'){
                    $style = "display:none";
                }
            }

            //如果是工作台，隐藏其它只保留 平台书名
            if( stristr(ACTION_NAME,'mycenter_')){
                if($key != 'platform_ids' && $key != 'book_id'){
                    $style = "display:none";
                }
            }

            //如果是热度 爆款或内部库
            if( stristr(ACTION_NAME,'hot_') || stristr(ACTION_NAME,'inside_')){
                if($key == 'hot'){
                    $style = "display:none";
                }
            }

            // 2022-11-10 编辑器和工作台显示， 这里强烈建议开启
            // if( stristr(ACTION_NAME,'my') && $key == 'type'){
            //     $style = "";
            // }
            //如果是小说 需要展开下拉功能
            if($key == 'book_id'){
                $search .= '<div style="display: flex;align-items: flex-start;margin: 10px 5px;'.$style.'"><ul class="navs clearfix bookName" >';
            }else{
                $search .= '<ul class="navs clearfix" style="margin: 10px 5px;'.$style.'">';
            }
            $search .='<li><span class="text-muted">'.$arrD[$key]['name'].'：</span></li>';
            foreach ($value as $k => $v) {
                $class = "";
                $dataArr[$key][$k]['ischecked'] = 0;
                if( $key == 'platform_ids' && isset($idinfo['platform_ids']) && $idinfo['platform_ids'] ==  $v['id']){
                    $class = "active";
                }
                // 如果参数上有这个选中
                if(isset($param[$key]) && $param[$key] == $v['id'] && !isset($idinfo['platform_ids'])){
                    $class = "active";
                    $dataArr[$key][$k]['ischecked'] = 1; 
                }
                //默认是全部
                if(isset($param[$key]) && $param[$key] == 999999 and  $v['id'] == 999999){
                    $class = "active";
                }
                if(!isset($param[$key]) && $v['id'] == 999999){
                    $class = "active";
                }
                //如果是编辑器 或工作台 ，要显示每个平台 的个数
                if( $key == 'platform_ids' && stristr(ACTION_NAME, 'my')) {
                    $act = stristr(ACTION_NAME, 'my_') ? 231 : 232;
                    $count = $this->menuNum($act, $type, $v['id']);
                    // dump($act);exit;
                    $v['name'] = $v['name']."($count)";
                }
                //分类 标签 频道 书名 男女要分2种颜色
                if($key == 'category_id' || $key == 'tag_ids' || $key == 'channel'  || $key == 'book_id'){
                    $v['sex'] = $v['sex']??'';
                    if($v['sex']){
                        $colorArr = [
                            "男频"=> "#777",
                            "女频"=> "#a94442",
                            "全部"=> "#333",
                            "其它"=> "#333",
                        ];
                        $colorArr[$v['sex']] = $colorArr[$v['sex']]??"#333";//默认
                        $class .= '" style="color:'.$colorArr[$v['sex']].'"';
                        // if($key == 'book_id'){
                        //     $class .= $v['sex'] == "男频" ? ' " style="color:#777"':' " style="color:#a94442"';
                        // }else{
                        //     // $class .= $v['sex'] != "男频" ? ' text-danger':' text-primary';
                        //     $class .= $v['sex'] == "男频" ? ' " style="color:#777"':' " style="color:#a94442"';
                        // }
                    }
                }
                //如果有图片的展示图标
                if(isset($v["icon"])){
                    $v['name'] = '<i class="iconfont '.$v["icon"].'"></i> '.$v['name'];
                }
                $newParam = $param;
                $newParam[$key] = $v['id'];
                $newurl = $url."?".http_build_query($newParam);
                $show_types = $v["types"]??[];
                //分类，对不同的type 显示不同
                if ($key == 'type' && !in_array($type, $show_types)){
                }else{
                    $search .='<li><a href="'.$newurl.'" class="'.$class.'">'.$v['name'].'</a></li>';
                }
            }
            $search .= "</ul>";
            if(in_array($key,["book_id"]) ){
                $search .= '<div class="spread"> <span>展开</span> <div id="create_'.$key.'"> <i class="fa fa-plus"></i> 添加 </div></div>';
            }
            if($key == 'book_id'){
                $search .= "</div>";
            }
        }
        $typeid = $type;
        $this->assign( compact('search') );
        $this->assign( compact('dataArr', 'arrD', 'typeid') );
	}

    public function add() {
        // return $this->error("失败！");
        if(IS_POST){
            $post = input('post.');
            if(isset($post['score']) && $post['score'] >= 100){
                return $this->error("评分最高99");
            }
            if(isset($post['tag_ids'])){
                $post['tag_ids'] = is_array( $post['tag_ids']) ?  implode(",", $post['tag_ids']) : $post['tag_ids'];
            }
            if(isset($post['platform_ids'])){
                //多个平台以，号分开
                $post['platform_ids'] =  is_array( $post['platform_ids']) ?  implode(",", $post['platform_ids']) : $post['platform_ids'];
            }
            if(isset($post['hot'])){
                $post['hot'] = is_array( $post['hot']) ?  implode(",", $post['hot']) : $post['hot'];
            }
            if( empty($post['id']) ){
                $post['uid'] = session('user_auth.uid');
                $post['create_time'] = time();
                // 文案批量上传
                if(isset($post['ebook'])&&$post['ebook']){
                    if( in_array($post['platform_ids'], [3,4])){
                        $list = $this->uploadDownTxt->read_txt_3($post['ebook']);
                        // dump($list);exit;
                    }else{
                        $list = $this->uploadDownTxt->read_txt($post['ebook']);
                    }
                    unset($post['ebook']);
                    unset($post['id']);
                    $insertData = [];
                    $err = '';
                    foreach ($list as $content) {
                        $isHave = db('ads_material')->where('content', $content)->find();
                        if ($isHave) {
                            $err .= $content . "<br>";
                            continue;
                        }
                        $insertData[] = array_merge($post, ['content'=>$content]);
                    }
                    // 数据太多 分批插入
                    $list = array_chunk($insertData, 1000);
                    foreach($list as $saveitem){
                        db('ads_material')->insertAll($saveitem);
                    }
                    return $this->success('添加成功，已存在文案如下:' .$err);
                }else{
                    //如果是媒体文件 ，有http有英文逗号分新的一条
                    if(stristr($post['content'], 'http') && stristr($post['content'], ',')){
                        $contents = explode(',', $post['content']);
                        $titles   =  [];
                        $post['title'] = $post['title']??"";
                        if(isset($post['title']) && stristr($post['title'], ',')){
                            $titles  =  explode(',', $post['title']);
                        }
                        $covers   =  [];
                        $post['cover'] = $post['cover']??"";
                        if(isset($post['cover']) && stristr($post['cover'], ',')){
                            $covers  =  explode(',', $post['cover']);
                        }
                        unset($post['id']);
                        $insertData = [];
                        foreach ($contents as $k=>$content) {
                            if(empty($content)) continue;
                            $title        = $titles[$k]??$post['title'];
                            $cover        = $covers[$k]??$post['cover'];
                            $insertData[] = array_merge($post, ['content'=>$content, 'title'=> $title, 'cover'=> $cover]);
                        }
                        // dump($insertData);exit;
                        db('ads_material')->insertAll($insertData, true);
                        $id = db('ads_material')->getLastInsID();
                        action_log2(0, $post['platform_ids'], 'add');
                    }else{
                        $isHave = db('ads_material')->where('content', $post['content'])->find();
                        if ($isHave) {
                            return $this->error("失败！,当前文案已存在");
                        }
                        //文案单条上传
                        $id =db('ads_material')->insertGetId($post);
                        action_log2($id, $post['platform_ids'], 'add');
                    }
                }
            }else{
                
                $post['update_time'] = time();
                db('ads_material')->update($post);
                action_log2($post['id'], $post['platform_ids']);
            }
            return $this->success("添加成功！");
        }
        return $this->error("失败！");
    }
    
    public function del() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
		$result    = db('ads_material')->where($map)->delete();
        action_log2($id, 999);
		if (false !== $result) {
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}

    //复制或下载
    public function copy(){
        $id = input('param.id');
        if (empty($id)) {
			return $this->error("非法操作！");
		}
        $db = stristr(input('param.source'), 'my') ? 'ads_material_my' : 'ads_material';
        $result    = db($db)->where("id=".$id)->setInc('copy_click_num', 1);
        if($db == 'ads_material'){
            //如果是素材库，非工作台编辑器复制或下载 的保存下记录
            $insertData = [
                "uid" => session('user_auth.uid'),
                'ads_material_id' => $id,
                "create_time" => time()
            ];
            db("ads_material_down_log")->insert($insertData);
        }
        $platform_ids = db($db)->where("id=".$id)->value('platform_ids');
        action_log2($id, $platform_ids);
        if (false !== $result) {
			return $this->success("复制成功！");
		} else {
			return $this->error("复制失败！");
		}
    }

    //加入编辑台成功
    public function addFollow() {
        $id = input('param.id');
        if (empty($id)) {
			return $this->error("非法操作！");
		}
        $uid = session('user_auth.uid');
        $insertData = db('ads_material')->field('id as ads_material_id,content,channel,type,platform_ids,category_id,tag_ids,book_id,title,cover')->where("id=".$id)->find();
        $insertData['uid'] = $uid;
        $insertData['book_id'] = 0;
        $insertData['create_time'] = time();
        $insertData['update_time'] = time();
        db('ads_material_my')->insert($insertData);
        db('ads_material')->where("id=".$id)->setInc('follow_num', 1);
        return $this->success("加入编辑台成功！");
    }

    //上报到公众库
    public function uploadMaterial() {
        $id = input('param.id');
        if (empty($id)) {
			return $this->error("非法操作！");
		}
        $uid = session('user_auth.uid');
        $insertData = db('ads_material_my')->field('id as ads_material_id,content,channel,type,platform_ids,category_id,tag_ids,book_id,update_time,title,uid,magnitude_num,hot,status,cover')->where("id=".$id)->find();
        // $insertData['uid'] = $uid;
        $insertData['create_time'] = time();
        unset($insertData['ads_material_id']);
        $result = db('ads_material')->where("ads_material_my_id=".$id)->find();
        if(empty($insertData['book_id'] )){
            return $this->error("请先绑定好书名，再上报到公众库");
        }
        // if($insertData['status'] != 1){
        //     return $this->error("管理员没过稿，无法上报到公众库");
        // }
        if($result){
            $res = db('ads_material')->where("id=".$result['id'])->update($insertData);
            action_log2($result['id'], $result['platform_ids']);
            return $this->success("同步数据到公众库成功");
        }else{
           
            $insertData['ads_material_my_id'] = $id;
            $id = db('ads_material')->insertGetId($insertData);
            action_log2($id, $result['platform_ids']);
            return $this->success("上报到公众素材成功！");
        }
    }

    //删除我的素材
    public function del_my() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
		$result    = db('ads_material_my')->where($map)->delete();

        action_log2($id, 999);
		if (false !== $result) {
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}

    //添加我的素材
    public function add_my() {
        if(IS_POST){
            $post = input('post.');
            if(isset($post['tag_ids'])){
                $post['tag_ids'] = is_array( $post['tag_ids']) ?  implode(",", $post['tag_ids']) : $post['tag_ids'];
            }
            if(isset($post['platform_ids'])){
                $post['platform_ids'] =  is_array( $post['platform_ids']) ?  implode(",", $post['platform_ids']) : $post['platform_ids'];
            }
            if(!isset($post['ads_material_id'])){
                $post['ads_material_id'] = 0;
            }
            // dump($post);exit;
            if( !$post['id'] ){
                $post['hot'] = 3; //默认是内
                $post['uid'] = session('user_auth.uid');
                $post['create_time'] = time();
                //如果是媒体文件 ，有http有英文逗号分新的一条
                if(stristr($post['content'], 'http') && stristr($post['content'], ',')){
                    $contents = explode(',', $post['content']);
                    $titles   =  [];
                    $post['title'] = $post['title']??"";
                    if(isset($post['title']) && stristr($post['title'], ',')){
                        $titles  =  explode(',', $post['title']);
                    }
                    $covers   =  [];
                    $post['cover'] = $post['cover']??"";
                    if(isset($post['cover']) && stristr($post['cover'], ',')){
                        $covers  =  explode(',', $post['cover']);
                    }
                    unset($post['id']);
                    $insertData = [];
                    foreach ($contents as $k=>$content) {
                        if(empty($content)) continue;
                        $title        = $titles[$k]??$post['title'];
                        $cover        = $covers[$k]??$post['cover'];
                        $insertData[] = array_merge($post, ['content'=>$content, 'title'=> $title, 'cover'=> $cover]);
                    }
                    // dump($insertData);exit;
                    db('ads_material_my')->insertAll($insertData, true);
                    $id = db('ads_material_my')->getLastInsID();
                    action_log2($id, $post['platform_ids'], 'add');
                }else{
                    $id = db('ads_material_my')->insertGetId($post);
                    action_log2($id, $post['platform_ids'], 'add');
                }
            }else{
                // $post['update_time'] = time();
                $my = db('ads_material_my')->find($post['id']);
                $post['ads_material_id'] = $my['ads_material_id'];
                $post['type'] = $my['type'];
                db('ads_material_my')->where("id=".$post['id'])->update($post);
                action_log2($post['id'], $post['platform_ids']);
            }
            return $this->success("添加成功！");
        }
        return $this->error("失败！");
    }

    //编辑器修改内容
    public function editMyContent(){
        if(IS_POST){
            $post = input('post.');
            if($post['id']){
                $post["is_edit"] = 2;//状态修改成工作台
                $post["update_time"] = time();
                $post['hot'] = 3;
                db('ads_material_my')->where("id=".$post['id'])->update($post);
                return $this->success("修改成功！");
            }else{
                $type = input('post.type', 1);
                $insertData = [
                    "type" => $type,
                    'ads_material_id' => 0,
                    'uid' =>  session('user_auth.uid'),
                    'platform_ids'=>input('post.platform_ids'),
                    'content' => $post['content'],
                    'title' => $post['title'],
                    'create_time' => time(),
                    'update_time' => time(),
                    'is_edit' => 2,
                    'hot' => 3
                ];
                db('ads_material_my')->insert($insertData);
                // dump(db('ads_material_my')->getLastInsID());exit;
                return $this->success("添加成功");
            }
        }
        return $this->error("失败！");
    }

    //编辑器 - 添加一条新素材
    public function add_my_one() {
        $uid  = session('user_auth.uid');
        $type = input('post.type', 1);
        $post = [
            "uid" => $uid,
            "type" => $type,
            'ads_material_id' => 0,
            'create_time' => time(),
            'update_time' => time(),
            'platform_ids'=>input('post.platform_ids')
        ];
        db('ads_material_my')->insert($post);
        return $this->success("添加成功！");
    }

    //用户下拉
    private function getUserList() {
        $uid  = session('user_auth.uid');
        $uids = $this->getUids($uid);
        $map = [];
        if(session('user_auth.group') != 999){
            $map["uid"] = ["in", $uids];
        }
        $userlist2 = db('member')->where( $map  )->column("uid,username"); //工作台显示当前账号子账号下的
        $userlist  = db('member')->column("uid,username"); // 公众库用户列表显示全部的
        $this->assign(compact('userlist','userlist2', 'uid'));
        return $userlist2;
    }

    //pid下级的全部uid
    public function getUids($uid) {
        $members = db("member")->column('uid as id,pid','uid');
        $pid_sub = $this->recursion($members, $uid);
        $pid_sub_ids = array_column($pid_sub, 'uid');
        $uids  = array_merge($pid_sub_ids, [$uid]);
        return $uids;
    }



    //下载 txt
    public  function down_txt() {
        $id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
        $chapter = db('ads_material_my')->where($map)->order("update_time desc,id desc")->column('id,content');
        if(empty($chapter)){
            $this->error("没有内容可下载");
        }
        action_log2($id, 1);
        $this->uploadDownTxt->down_txt($chapter);
	}

    //下载 抖音 txt
    public  function down_douyin_txt() {
        $id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
        $chapter = db('ads_material_my')->where($map)->order("update_time desc,id desc")->column('id,content');
        if(empty($chapter)){
            $this->error("没有内容可下载");
        }
        action_log2($id, 3);
		$this->uploadDownTxt->down_txt3($chapter);
	}

    //过稿操作, 只能一条过稿，不然没绑定 书名的就会过稿失败
    public function change_status() {
       
        $id = input('param.id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
        $map = [];
		$map['id'] = array('IN', $id);
        $materialMy = db('ads_material_my')->where($map)->find();
        if (empty($materialMy['book_id'])) {
			return $this->error("需要先绑定书名才能过稿");
		}

        db('ads_material_my')->where($map)->update(['status' => 1]);
        //保存到书库中
        try {
            if($materialMy['status'] != 1 || true) { //这里可以多次过稿将素材 添加到书库那边把true修改成false就只能一次了
                $obj = new \app\admin\model\AdsBookMaterial();
                $obj->saveBookMaterial($materialMy);
            }
        } catch (\Exception $th) {
            return $this->error("保存出错：".$th->getMessage());
        }
        action_log2($id, $materialMy['platform_ids']);
        return $this->success("已过稿");
    }

    //左边菜单 工作台 个数
    public function menuNum($menuid = 0, $type=0, $platform_id=0) {
        $type    =  input('param.type', $type);
        $uid     = session('user_auth.uid');
        $menu    = [
            ['id' => 231, 'name' => '编辑台', 'count' => 0, 'type' => 1],
            ['id' => 232, 'name' => '工作台', 'count' => 0, 'type' => 1],
            ['id' => 260, 'name' => '图片-工作台', 'count' => 0, 'type' => 6],
            ['id' => 261, 'name' => '视频-工作台', 'count' => 0, 'type' => 3],
        ];
        $map     = ["uid" => $uid];
        $where   = "1=1";
        if($type){
            $where .= " and type in ($type)";
        }
        if($platform_id){
            $where .= " and FIND_IN_SET($platform_id, platform_ids)";
        }
        // echo $where;exit;
        if($menuid > 0){
            if($menuid == 231){
                //    return db('ads_material_my')->where($where)->where("is_edit", 1)->where($map)->count();
                return db('ads_material_my')->where($where)->where("is_edit", 1)->whereTime('update_time','>=', date('Y-m-d'))->where($map)->count();
            }
            if(in_array($menuid, [232,260,261])){
                $map['uid'] = ["in", $this->getUids($uid)];
                return db('ads_material_my')->where($where)->where("is_edit", 2)->where($map)->whereTime('update_time','>=', date('Y-m-d'))->count();
            }
        }
        foreach ($menu as $k => $v) {
            $count = 0;
            if($v['id'] == 231){
                // $v['count'] = db('ads_material_my')->where($where)->where("is_edit", 1)->where($map)->count();
                $v['count'] = db('ads_material_my')->where($where)->where("is_edit", 1)->whereTime('update_time','>=', date('Y-m-d'))->where($map)->count();
            }
            if(in_array($v['id'], [232,260,261])){
                // $map['type'] = $v['type'];
                $where =  "type in (".$v['type'].")";
                $map['uid'] = ["in", $this->getUids($uid)];
                $v['count'] = db('ads_material_my')->where($where)->where("is_edit", 2)->where($map)->whereTime('update_time','>=', date('Y-m-d'))->count();
                // echo  db('ads_material_my')->getLastSql();exit;
            }
            $menu[$k] = $v;
        }
        $data = [
            'code' => 0,
            'msg'  => 'success',
            'data' => $menu
        ];
        return json($data);
    }

    /**
    * 根据父级id查找子级数据
    * @param $data     要查询的数据
    * @param int $pid 父级id
    */
    private function recursion($data, $pid = 0) {
       static $child = [];   // 定义存储子级数据数组
        foreach ($data as $key => $value) {
            if ($value['pid'] == $pid) {
                $child[] = $value;   // 满足条件的数据添加进child数组
                unset($data[$key]);  // 使用过后可以销毁
                $this->recursion($data, $value['id']);   // 递归调用，查找当前数据的子级
            }
        }
        return $child;
    }

    //公用排序
    private function getOrder(){
        $order = '';
        $pub_sort = input('get.pub_sort');
        switch ($pub_sort) {
            case 1:
                $order = "id desc";
                break;
            case 2:
                $order = "score desc";
                break;
            case 3:
                $order = "score asc";
                break;
            case 4:
                $order = "copy_click_num desc";
                break;
            case 5:
                $order = "copy_click_num asc";
                break;
            case 6:
                $order = "follow_num desc";
                break;
            case 7:
                $order = "follow_num asc";
                break;
            case 8:
                $order = "magnitude_num desc";
                break;
            case 9:
                $order = "magnitude_num asc";
                break;
            case 10:
                $order = "book_id desc";
                break;
            case 11:
                $order = "book_id asc";
                break;
            case 12:
                $order = "status desc";
                break;
            case 13:
                $order = "status asc";
                break;
            case 14:
                $order = "create_time desc";
                break;
            case 15:
                $order = "create_time asc";
                break;

            default:
                # code...
                break;
        }
        return $order;
    }

    //全库下载 
    public function down_all(){
        $db  = input('param.source') == 'mycenter' ? 'ads_material_my' : 'ads_material';
        $act = input('get.act');
        $map = "1=1";
        $platform_ids = input('param.platform_ids');
        $type = input('param.type');
        $map .= " and type={$type} and FIND_IN_SET($platform_ids, platform_ids)";
        if(stristr($act, 'hot_')){
            //1，爆，2量，3量级大于1万，4评分95分以上
            $map .= ' and ( '.$this->hotLevelSearch().")";
        }
        $uid  = session('user_auth.uid');
        $uids = $this->getUids($uid);
        $map2 = [];
        if(session('user_auth.group') != 999){
            $map2["uid"] = ["in", $uids];
        }
        $order = 'id desc';
        if(input('param.source') == 'mycenter'){
            // $uid   = session('user_auth.uid');
            // $map2["uid"] = $uid;
            $map2['is_edit']  = 2;
            $order = 'update_time desc';
            if(input('get.startdata') && !input('get.keyword')){
                $startdata = (input('get.startdata'));
                $enddata   = (input('get.enddata'));
                $startdata1 = strtotime($startdata);
                $enddata1   = strtotime($enddata." 23:59:59");
                $map .= " and update_time>=$startdata1 and update_time<=$enddata1";
            }
        }
        // echo $order;exit;
        $chapter = db($db)->where($map)->where($map2)->order($order)->column('id,content');
        // dump($chapter);exit;
        if(empty($chapter)){
            $this->error("没有内容可下载");
        }
        action_log2(array_keys($chapter), 999);
        $this->uploadDownTxt->down_all($chapter, $platform_ids);
    }

    //工作台-下放功能
    public function distribution_send()
    {
        $ids   = input('post.ids');
        $uids  = input('post.uids');
		if (empty($ids) || empty($uids)) {
			return $this->error("非法操作！");
		}
        $ids  = !stristr($ids, ',') ? [$ids] : explode(",", $ids);
        $uids = !stristr($uids, ',') ? [$uids] : explode(",", $uids);
        $map = [];
		$map['id'] = array('IN', $ids);
        $materialMy = db('ads_material_my')->where($map)->select();
        $obj = new \app\admin\model\AdsBookMaterial();
        $succ_count = 0;
        $faild_count = 0;
        $faild_ids = [];
        foreach ($materialMy as $k => $v) {
            if(empty($v['book_id'])){
                $faild_ids[] = $v['id'];
                $faild_count++;
                continue;
            }
            foreach ((array)$uids as $uid) {
                //判断一下是否下发过
                $map = [
                    "ads_material_my_id" => $v['id'],
                    'uid' => $uid
                ];
                $id =  db("ads_book_material")->where($map)->value('id');
                if($id){
                    //下发过的不再下发了
                    // continue;
                }
                $obj->saveBookMaterial($v, $uid);
            }
            $exists = [];
            if( $v['distribution_uids']){
                $exists = explode(",", $v['distribution_uids']);
            }
            $distribution_uids =  array_merge($exists, $uids);
            $distribution_uids = array_unique($distribution_uids);//去重复
            db('ads_material_my')->where("id", $v['id'])->update(['is_distribution' => 1, 'distribution_uids' => implode(",", $distribution_uids)]);
            
            action_log2($v['id'], $v['platform_ids']);
            //如果加成功了，将这里
            $succ_count++;
        }
       
        if($faild_count == 0){
            $this->success("全部下发成功");
        }
        // return $this->error("成功下发 {$succ_count} 条，失败{$faild_count} 条, 失败原因： 没绑定书名, 编号：".implode(",", $faild_ids));
        return $this->error("成功下发 {$succ_count} 条，失败{$faild_count} 条, 失败原因： 没绑定书名");
    }
}